# -*- coding: utf-8 -*-
import sys
import MySQLdb
'''
python进行事务的的操作

'''

class TransferMoney(object):
    def __init__(self,conn):
        self.conn = conn
    def transer(self,source_accid,target_accid,money):
        try:
            self.check_acctid_available(source_accid)
            self.check_acctid_available(target_accid)
            self.has_enough_money(source_accid,money)
            self.reduce_money(source_accid,money)
            self.add_money(target_accid,money)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            raise e

    def check_acctid_available(self, accid):
        cursor = self.conn.cursor()
        try:
            sql = "select * from accout where acctid = ％s"%accid
            cursor.execute(sql)
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("账号%s不存在"%accid)
        finally:
            cursor.close()

    def has_enough_money(self, source_accid, money):
        pass

    def reduce_money(self, accid, money):
        cursor = self.conn.cursor()
        try:
            sql = "update accout set money=money - ％s where accid = %s" %(money,accid)
            cursor.execute(sql)
            rs = cursor.fetchall()
            if cursor.rowcount != 1: #数据影响了多少行
                raise Exception("账号%s没有足够的钱" % accid)
        finally:
            cursor.close()
    def add_money(self, target_accid, money):
        pass


if __name__ == "__main__":
    source_acctid = sys.argv[1]
    target_acctid = sys.argv[2]
    money = sys.argv[3]

    conn = MySQLdb.connect(
        host='120.26.85.119',
        port=3307,
        user='root',
        passwd='042011_cyq',
        db='dev_zf',
        charset='utf8'
    )
    tr_money = TransferMoney(conn)

    try:
        tr_money.transer(source_acctid,target_acctid,money)
    finally:
        conn.close()

